<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>开汽运主单</title>
        <% include("/common/common_css_js.html"){} %>
    </head>
    <body>

        <div style="width: 1000px;margin: 5px 0;margin-left: 5px;">
            <% if(so.hasPermission("bMasterBillAuto:save")){%>
                <a id="saveBtn" class="mini-button" iconCls="icon-save" onclick="saveMasterBill()">保存</a>
            <% } %>
        </div>

        <div id="masterBillForm" style="padding-bottom: 5px;" class="mini-fit">

            <span>主单号:</span><input id="id" name="id" value="${id!}" enabled="false" emptyText="请输入主单号"  class="mini-textbox" selectOnFocus="true" required="true" requiredErrorText="主单号不能为空" />

            <span>承运方式:</span><input id="transportWayId" name="transportWayId" class="mini-combobox" style="width:150px;" textField="name" valueField="id" emptyText="请选择..."
                                     required="true" allowInput="false" showNullItem="false" nullItemText="请选择..." requiredErrorText="没有选择承运方式" onvaluechanged="transportWayIdChange"/>

            <span>承运单位:</span>
            <div id="transportUnitId" name="transportUnitId" class="mini-combobox" style="width:250px;"  popupWidth="400" textField="name" valueField="id"
                 required="true" requiredErrorText="承运单位不能为空" showNullItem="false" nullItemText="请选择..."
                 multiSelect="false" >
                <div property="columns">
                    <div header="单位名称" field="name"></div>
                    <div header="单位电话" field="phone"></div>
                </div>
            </div>

            <span>承运主单号:</span><input id="transportUnitMasterBillCodeIds" name="transportUnitMasterBillCodeIds" emptyText="承运主单号"  class="mini-textbox" style="width: 200px" selectOnFocus="true" required="true" requiredErrorText="承运主单号不能为空" />

            <div style="margin-top: 5px"></div>
            <span>始发站:</span>
            <input id="startCityId" name="startCityId" class="mini-treeselect"
                   multiSelect="false" valueField="id" textField="name"  virtualScroll="true"
                   parentField="pid" allowInput="true" valueFromSelect="true"
                   style="width: 250px;" expandOnLoad="true" required="true" nullItemText="请选择..." />

            <span>目的站:</span>
            <input id="destCityId" name="destCityId" class="mini-treeselect"
                   multiSelect="false" valueField="id" textField="name"  virtualScroll="true"
                   parentField="pid" allowInput="true" valueFromSelect="true"
                   style="width: 250px;" expandOnLoad="true" required="true" nullItemText="请选择..." />

            <span>线路:</span><input id="autoLineRoadName" name="autoLineRoadName" emptyText="请填写线路"  class="mini-textbox" style="width: 150px" selectOnFocus="true" required="false" requiredErrorText="线路不能为空" />

            <span>派送方式:</span><input id="sendWayId" name="sendWayId" class="mini-combobox" style="width:150px;" textField="name" valueField="id" emptyText="请选择..."
                                     required="true" allowInput="false" showNullItem="false" nullItemText="请选择..." requiredErrorText="没有选择派送方式"/>

            <div style="margin-top: 5px"></div>
            <span>提货点:</span>
            <div id="pickUpPointId" name="pickUpPointId" class="mini-combobox" style="width:250px;"  popupWidth="400" textField="name" valueField="id"
                 required="true" requiredErrorText="提货点不能为空"
                 allowInput="true"
                 emptyText="提货点名称"
                 onvaluechanged="pickUpPointIdChange">
                <div property="columns">
                    <div header="提货点名称" field="name"></div>
                    <div header="提货点电话" field="phone"></div>
                    <div header="提货点地址" field="address"></div>
                </div>
            </div>
            <input id="pickUpPointName" name="pickUpPointName" style="width:250px;"  emptyText="提货点名称"  class="mini-textbox" selectOnFocus="true" visible="false"  required="false" requiredErrorText="提货点名称不能为空"/>
            <input id="pickUpPointPhone" name="pickUpPointPhone" style="width:100px;"  emptyText="提货点电话"  class="mini-textbox" selectOnFocus="true" required="true" requiredErrorText="提货点电话不能为空"/>
            <input id="pickUpPointAddress" name="pickUpPointAddress" style="width:250px;"  emptyText="提货点地址"  class="mini-textbox" selectOnFocus="true" required="true" requiredErrorText="提货点地址不能为空"/>

            <div style="margin-top: 5px"></div>
            <span>车牌号:</span><input id="licensePlateNumber" name="licensePlateNumber" emptyText="车牌号"  class="mini-textbox" style="width: 150px" selectOnFocus="true" required="true" requiredErrorText="车牌号不能为空" />
            <span>走货时间:</span><input id="deliveryTime" name="deliveryTime" class="mini-datepicker" style="width:200px;"  nullValue="null" required="true" requiredErrorText="走货时间不能为空"
                   format="yyyy-MM-dd H:mm:ss" timeFormat="H:mm:ss" showTime="true" showOkButton="true" showClearButton="true"/>

            <span>驾驶员:</span><input id="driver" name="driver" emptyText="驾驶员"  class="mini-textbox" style="width: 150px" selectOnFocus="true" required="true" requiredErrorText="驾驶员不能为空" />
            <span>驾驶员电话:</span><input id="driverPhone" name="driverPhone" emptyText="驾驶员电话"  class="mini-textbox" style="width: 150px" selectOnFocus="true" required="true" requiredErrorText="驾驶员电话不能为空" />

            <span>货物类型:</span><input id="goodsTypeId" name="goodsTypeId" class="mini-combobox" style="width:150px;" textField="name" valueField="id" emptyText="请选择..."
                                     required="true" allowInput="false" showNullItem="false" nullItemText="请选择..." requiredErrorText="没有选择货物类型"/>

            <div style="margin-top: 5px"></div>
            <div style="display: flex;justify-content: flex-start;width: 1500px;">
                <div style="margin-top: 80px;">
                    <span>分单列表:</span>
                </div>
                <div style="width: 5px"></div>
                <div style="width:1200px;border-bottom:0;padding:0px;">
                    <div class="mini-toolbar" style="width:1200px;border-bottom:0;padding:2px;">
                        <span>分单号:</span>
                        <div id="billId" name="billId" class="mini-autocomplete" style="width:150px;"  popupWidth="1000" textField="id" valueField="id"
                             requiredErrorText="分单号不能为空"
                             multiSelect=false
                             searchField="key"
                             allowInput="true"
                             emptyText="输入分单号"
                             onvaluechanged="billIdChanged"
                             onfocus="billIdFocus()">
                            <div property="columns">
                                <div header="分单号" field="id" width="60"></div>
                                <div header="运输种类" field="transportSpeciesId" data-options='{cacheName:"sysDic"}' renderer="commonRender"></div>
                                <div header="物品名称" field="goodsName"></div>
                                <div header="包装" field="packingWayId" data-options='{cacheName:"sysDic"}' renderer="commonRender"></div>
                                <div header="剩余件数" field="totalNumber"></div>
                                <div header="剩余实际重量" field="actualWeight"></div>
                                <div header="剩余计费重量" field="chargeableWeight"></div>
                                <div header="重量费率" field="weightRate"></div>
                                <div header="剩余体积" field="volume"></div>
                                <div header="体积费率" field="volumeRate"></div>
                                <div header="航班名称" field="flightName"></div>
                                <div header="航班日期" field="flightDate" dateFormat="yyyy-MM-dd" renderer="ondayRenderer"></div>
                                <div header="开单人" field="createUserId" data-options='{cacheName:"sysUser"}' renderer="commonRender"></div>
                            </div>
                        </div>
                        <span class="separator"></span>
                        <a class="mini-button" iconCls="icon-remove" onclick="removeSelectedRow"  tooltip="剔除...">剔除</a>
                    </div>
                    <div id="selectedBillDatagrid" class="mini-datagrid" style="width:1200px;height:200px;"
                         idField="id"
                         showPager="false"
                         allowCellEdit="true" allowCellSelect="true" multiSelect="true"
                         showGroupsSummary="true" showSummaryRow="true" summaryPosition="bottom"
                         editNextOnEnterKey="true"  editNextRowCell="true"
                         oncellendedit="gridCellEndEdit"
                    >
                        <div property="columns">
                            <div type="checkcolumn"></div>
                            <div field="id" headerAlign="center"  width="50" >分单号</div>
                            <div field="goodsName" width="80" headerAlign="center"  >物品名称</div>
                            <div field="packingWayId" width="40" headerAlign="center" data-options='{cacheName:"sysDic"}' renderer="commonRender">包装</div>
                            <div field="totalNumber" width="40" headerAlign="center" align="right" summaryType="sum">配载件数
                                <input property="editor" class="mini-textbox"/>
                            </div>
                            <div field="actualWeight" width="50" headerAlign="center" align="right" summaryType="sum">配载实际重量
                                <input property="editor" class="mini-textbox"/>
                            </div>
                            <div field="chargeableWeight" width="50" headerAlign="center" align="right" summaryType="sum">配载计费重量
                                <input property="editor" class="mini-textbox"/>
                            </div>
                            <div field="weightRate" width="40" headerAlign="center" align="right" >重量费率</div>
                            <div field="volume" width="40" headerAlign="center" align="right" summaryType="sum">配载体积
                                <input property="editor" class="mini-textbox"/>
                            </div>
                            <div field="volumeRate" width="40" headerAlign="center" align="right" >体积费率</div>
                            <div field="flightName" width="40" headerAlign="center" align="center">班次名称</div>
                            <div field="flightDate" width="40" headerAlign="center" align="center" dateFormat="yyyy-MM-dd" renderer="ondayRenderer" >班次日期</div>
                            <div field="createUserId" width="40" headerAlign="center" data-options='{cacheName:"sysUser"}' renderer="commonRender">开单人</div>
                        </div>
                    </div>
                </div>
            </div>

            <div style="margin-top: 5px"></div>
            <span>总件数:</span><input id="totalNumber" name="totalNumber" value="0" emptyText="总件数"  class="mini-textbox" style="width: 100px" selectOnFocus="true" required="true"  />
            <span>实际重量:</span><input id="actualWeight" name="actualWeight" value="0" emptyText="实际重量"  class="mini-textbox" style="width: 100px" selectOnFocus="true" required="true" onvaluechanged="actualWeightChange"/>
            <span>计费重量:</span><input id="chargeableWeight" name="chargeableWeight" value="0" emptyText="计费重量"  class="mini-textbox" style="width: 100px" selectOnFocus="true" required="true" onvaluechanged="chargeableWeightChange" />
            <span>重量费率:</span><input id="weightRate" name="weightRate" value="0" emptyText="重量费率"  class="mini-textbox" style="width: 100px" selectOnFocus="true" required="true" onvaluechanged="weightRateChange" />
            <span>体积:</span><input id="volume" name="volume" value="0" emptyText="体积"  class="mini-textbox" style="width: 100px" selectOnFocus="true" required="true" onvaluechanged="volumeChange" />
            <span>体积费率:</span><input id="volumeRate" name="volumeRate" value="0" emptyText="体积费率"  class="mini-textbox" style="width: 100px" selectOnFocus="true" required="true" onvaluechanged="volumeRateChange" />
            <span>运费合计:</span><input id="freightAmount" name="freightAmount" value="0" emptyText="运费合计"  class="mini-textbox" style="width: 100px" selectOnFocus="true" required="true" enabled="false" />

            <div style="margin-top: 5px"></div>

            <div style="display: flex;justify-content: flex-start;width: 1200px;">
                <div style="margin-top: 80px;">
                    <span>其他费用:</span>
                </div>
                <div style="width: 5px"></div>
                <div style="width:600px;border-bottom:0;padding:0px;">
                    <div class="mini-toolbar" style="width:600px;border-bottom:0;padding:0px;">
                        <a class="mini-button" iconCls="icon-add" onclick="addOtherChargesRow()" tooltip="增加...">增加</a>
                        <span class="separator"></span>
                        <a class="mini-button" iconCls="icon-remove" onclick="removeOtherChargesRow()" tooltip="删除...">删除</a>
                        <span class="separator"></span>
                        <a class="mini-button" iconCls="icon-ok" onclick="calcOtherCharges()" tooltip="计算其他费用...">计算其他费用</a>
                    </div>
                    <div id="otherChargeDatagrid" class="mini-datagrid" style="width:600px;height:200px;"
                         idField="id"
                         showPager="false"
                         allowCellEdit="true" allowCellSelect="true" multiSelect="true"
                         editNextOnEnterKey="true"  editNextRowCell="true" oncelleditenter="otherChargeDatagridEnter">
                        <div property="columns">
                            <div type="checkcolumn"></div>
                            <div type="indexcolumn">序号</div>
                            <div name="name"  field="name" headerAlign="center" allowSort="true" width="150" >其他费用名目
                                <input property="editor" class="mini-textbox" style="width:100%;" minWidth="200" />
                            </div>
                            <div name ="amount" field="amount" width="100" allowSort="true" >金额
                                <input property="editor" class="mini-textbox"  value="0" style="width:100%;"/>
                            </div>
                            <div field="comment" width="120" headerAlign="center" allowSort="true">备注
                                <input property="editor" class="mini-textarea" style="width:200px;" minWidth="200" minHeight="50"/>
                            </div>
                        </div>
                    </div>
                </div>
                <div style="width: 5px"></div>
                <div style="display: flex;flex-direction: column">
                    <span>金额:</span>
                    <input id="otherCharges" name="otherCharges" value="0" emptyText="其他费用"  class="mini-textbox" required="true" requiredErrorText="其他费用说明不能为空" enabled="false"/>

                    <div style="margin-top: 5px"></div>

                    <span>其他费用说明:</span>
                    <textarea id="otherChargesComment" name="otherChargesComment" class="mini-textarea" selectOnFocus="true" style="width: 400px;height: 160px" emptyText="输入其他费用说明" required="false"></textarea>

                </div>

            </div>

            <div style="margin-top: 5px"></div>

            <span>付款方式:</span><input id="masterBillPaymentMethodId" name="masterBillPaymentMethodId" class="mini-combobox" style="width:150px;" textField="name" valueField="id" emptyText="请选择..."
                                     required="true" allowInput="false" showNullItem="true" nullItemText="请选择..." requiredErrorText="没有选择付款方式"  onvaluechanged="masterBillPaymentMethodIdChange" />
            <span>总运费:</span><input id="totalFreightAmount" name="totalFreightAmount" value="0" emptyText="总运费"  class="mini-textbox" style="width: 100px" selectOnFocus="true" required="true" enabled="false" onvaluechanged="transportCostChange"/>

            <div style="margin-top: 5px"></div>
            <span>开单日期:</span><input id="openMasterBillDate" name="openMasterBillDate" class="mini-datepicker" style="width:200px;" value="${openMasterBillDate!}"  nullValue="null" format="yyyy-MM-dd"  showOkButton="true" showClearButton="true"/>

            <span>开单部门:</span><input id="openMasterBillDepartmentId" name="openMasterBillDepartmentId" value="${openMasterBillDepartmentId!}" class="mini-treeselect" style="width:250px;" textField="name" valueField="id" emptyText="请选择..."
                                     virtualScroll="true"   expandOnLoad="true" required="true" allowInput="false"  showNullItem="true" nullItemText="请选择..." requiredErrorText="没有选择开单部门"  />

            <span>开单人:</span><input id="openMasterBillUserId" name="openMasterBillUserId" value="${openMasterBillUserId!}" class="mini-combobox" style="width:150px;" textField="name" valueField="id" emptyText="请选择..."
                                    required="true" allowInput="false" showNullItem="true" nullItemText="请选择..." requiredErrorText="没有选择开单人" />

            <div style="margin-top: 5px"></div>
            <span>备注:</span><textarea id="comment" name="comment" class="mini-textarea" style="width: 80%;height: 50px" emptyText="请输入物品信息"  required="false"></textarea>

            <!-- 默认值隐藏区域  -->
            <input id="freightAmountStatusId" name="freightAmountStatusId" value="321" emptyText="运输费用结算状态ID"  class="mini-hidden" style="width: 100px" required="true" enabled="false" />

            <input id="dropAmount" name="dropAmount" value="0.0" emptyText="拉货累计金额"  class="mini-hidden" style="width: 100px" required="true" enabled="false" />
            <input id="settlementAmount" name="settlementAmount" value="0.0" emptyText="结算金额"  class="mini-hidden" style="width: 100px" required="true" enabled="false" />
            <input id="dropStatusId" name="dropStatusId" value="361" emptyText="拉货状态ID"  class="mini-hidden" style="width: 100px" required="true" enabled="false" />
            <input id="accountCheckStatusId" name="accountCheckStatusId" value="431" emptyText="对账状态ID"  class="mini-hidden" style="width: 100px" required="true" enabled="false" />
            <input id="settlementStatusId" name="settlementStatusId" value="321" emptyText="结算状态ID"  class="mini-hidden" style="width: 100px" required="true" enabled="false" />

            <input id="loadNativeBillIds" name="loadNativeBillIds" value=""  class="mini-hidden" style="width: 100px" required="false" enabled="false" />

            <!-- 实际配载总重量,用于成本分摊计算 -->
            <input id="actualLoadTotalWeight" name="actualLoadTotalWeight" value="0"  class="mini-hidden"  required="false" enabled="false" />

        </div>

        <script type="text/javascript">
            mini.parse();

            let masterBillForm = new mini.Form("#masterBillForm");

            // 承运方式
            let transportWayId = mini.get("transportWayId");
            // 承运单位
            let transportUnitId = mini.get("transportUnitId")
            // 承运单位主单号
            let transportUnitMasterBillCodeIds = mini.get("transportUnitMasterBillCodeIds");
            // 始发站
            let startCityId = mini.get("startCityId");
            // 目的站
            let destCityId = mini.get("destCityId");
            // 线路名称
            let autoLineRoadName = mini.get("autoLineRoadName");
            // 派货方式
            let sendWayId = mini.get("sendWayId");
            // 提货点 ID
            let pickUpPointId = mini.get("pickUpPointId");
            // 提货点 名称
            let pickUpPointName = mini.get("pickUpPointName");
            // 提货点 电话
            let pickUpPointPhone = mini.get("pickUpPointPhone");
            // 提货点 地址
            let pickUpPointAddress = mini.get("pickUpPointAddress");
            // 车牌号
            let licensePlateNumber = mini.get("licensePlateNumber");
            // 走货时间
            let deliveryTime = mini.get("deliveryTime");
            // 驾驶员
            let driver = mini.get("driver");
            // 驾驶员电话
            let driverPhone = mini.get("driverPhone");
            // 货物类型
            let goodsTypeId = mini.get("goodsTypeId");
            // 分单检索框
            let billId = mini.get("billId");
            // 获取分单列表
            let selectedBillDatagrid = mini.get("selectedBillDatagrid");
            // 总件数
            let totalNumber = mini.get("totalNumber");
            // 实际重量
            let actualWeight = mini.get("actualWeight");
            // 计费重量
            let chargeableWeight = mini.get("chargeableWeight");
            // 重量费率
            let weightRate = mini.get("weightRate");
            // 体积
            let volume = mini.get("volume");
            // 体积费率
            let volumeRate = mini.get("volumeRate");
            // 运费合计
            let freightAmount = mini.get("freightAmount");

            // 其他费用列表对象
            let otherChargeDatagrid = mini.get("otherChargeDatagrid");

            // 其他费用
            let otherCharges = mini.get("otherCharges");
            // 其他费用说明
            let otherChargesComment = mini.get("otherChargesComment");
            // 付款方式
            let masterBillPaymentMethodId = mini.get("masterBillPaymentMethodId");
            // 总运费
            let totalFreightAmount = mini.get("totalFreightAmount");
            // 开单日期
            let openMasterBillDate = mini.get("openMasterBillDate");
            // 开单部门
            let openMasterBillDepartmentId = mini.get("openMasterBillDepartmentId");
            // 开单人 ID
            let openMasterBillUserId = mini.get("openMasterBillUserId");
            // 备注
            let comment = mini.get("comment");

            // 实际配载重量,用于成本分摊
            let actualLoadTotalWeight = mini.get("actualLoadTotalWeight");

            // 定义承运方式
            let transportWay = {self:81, other:82};

            // 定义结算
            let settlementStatus ={uncleared:321, cleared:322};

            // 定义提货点类型
            let pickUpPointByType = {air:31, auto:32};

            // 获取操作类型
            let opType = "${opType!}"

            // 定义已经加入的分单ID
            let billIdArray=[];
            // 分单检索基本条件
            let baseUrl = "${base}/pages/native_bill_manage/getBNativeBillPojoByCnd?transportSpeciesId=72&pullDisposeId=232";

            $(function (){
                // 承运方式下拉列表
                let transportWayIdJsonData = commonRenderSysDicDropListByKey("sysDic","XT_DIC_TRANSPORT_WAY");
                transportWayId.load(transportWayIdJsonData);

                // 始发站
                let cityIdData = commonRenderDropList("city");
                startCityId.loadList(cityIdData, "id", "pid");

                // 目的站,同一个对象不能同时向两个控件绑定，所以做一次深度克隆
                let destCityIdData = public_deepClone(cityIdData);
                destCityId.loadList(destCityIdData, "id", "pid");

                // 派货方式
                let sendWayIdJsonData = commonRenderSysDicDropListByKey("sysDic","XT_DIC_SEND_WAY_TYPE");
                sendWayId.load(sendWayIdJsonData);

                // 加载汽运类型有提货点,实际上应该根据选择的目的站而选择提货但，现在没有做这个约束
                let pickUpPointIdJsonData = commonRenderPickUpPointByTypeId("pickUpPoint",pickUpPointByType.auto);
                pickUpPointId.load(pickUpPointIdJsonData);

                // 货物类型
                let goodsTypeIdJsonData=commonRenderSysDicDropListByKey("sysDic","XT_DIC_GOODS_TYPE");
                goodsTypeId.load(goodsTypeIdJsonData);

                // 主单付款方式 XT_DIC_AIR_MASTER_BILL_PAYMENT_METHOD
                let masterBillPaymentMethodIdJsonData= commonRenderSysDicDropListByKey("sysDic","XT_DIC_AIR_MASTER_BILL_PAYMENT_METHOD");
                masterBillPaymentMethodId.load(masterBillPaymentMethodIdJsonData);

                // 开单员数据
                let userJsonData = commonRenderDropList("sysUser");
                openMasterBillUserId.load(userJsonData);

                // 加载开单部门
                let departmentJsonData = commonRenderDropList("department");
                openMasterBillDepartmentId.loadList(departmentJsonData,"id","pid");
                openMasterBillDepartmentId.setValue("${openMasterBillDepartmentId!}");

                if(opType=="add"){
                    // 设置默认值
                    setDefaultValue()
                }
                else{
                    // 这只是查看,需要隐藏保存按钮
                    if(opType=="view"){
                        mini.get("saveBtn").hide();
                    }

                    // millisecondConvert
                    if(public_isEmpty(${pojo!})){
                        return;
                    }

                    // 1.根据承运方式 加载承运单位
                    let transportWayIdValue = public_toNumber('${pojo.transportWayId!}');
                    let transportUnitIdJsonData = [];
                    if(transportWayIdValue == transportWay.self){
                        // 这是自发，加载自个单位 sysCompany
                        transportUnitIdJsonData = commonRenderDropList("sysCompany");
                    }
                    else{
                        transportUnitIdJsonData = commonRenderDropList("outUnit");
                    }
                    transportUnitId.load(transportUnitIdJsonData);

                    let pojoObj = JSON.parse('${pojo!}');
                    // 将两个日期相关的值转为对应的年月日 时分秒
                    pojoObj.deliveryTime = millisecondConvert(pojoObj.deliveryTime);
                    pojoObj.openMasterBillDate = millisecondConvert(pojoObj.openMasterBillDate);
                    // 设定表单数据
                    masterBillForm.setData(pojoObj);

                    // 清空列表
                    billIdArray.splice(0,billIdArray.length);

                    // 加载主单中包含的分单
                    let loadBNativeBillPojoListJSONStr = '${loadBNativeBillPojoList!}';
                    let loadBNativeBillPojoList = JSON.parse(loadBNativeBillPojoListJSONStr);
                    if(!public_isEmpty(loadBNativeBillPojoList)){
                        if(loadBNativeBillPojoList.length>0){
                            for(let billObj of loadBNativeBillPojoList){
                                billIdArray.push(billObj.id);
                                selectedBillDatagrid.addRow(billObj);
                            }
                        }
                    }

                    // 设置检索分单框的下拉列表查询条件
                    setBillSearchCndUrl();

                    // 加载主单中包含的其他费用
                    let pojoOtherChargeListStr = '${pojoOtherChargeList!}';
                    let pojoOtherChargeList = JSON.parse(pojoOtherChargeListStr);
                    if(!public_isEmpty(pojoOtherChargeList)){
                        if(pojoOtherChargeList.length>0){
                            for(let otherChargeObj of pojoOtherChargeList){
                                otherChargeDatagrid.addRow(otherChargeObj);
                            }
                        }
                    }

                    // 如果是外发，则把承运主单号 设置为非必填
                    if(transportWayId.getValue() == transportWay.other){
                        transportUnitMasterBillCodeIds.set({required:false});
                    }

                }

            });

            /**
             * 设置控制值，要根据控制类型进行判断，调用不同的方法
             */
            function setObjValue(objId,value,selectType){
                let objType = objId.type;
                /*
                combobox
                textbox
                hidden
                autocomplete
                datepicker
                textarea
                button
                datagrid
                 */
                if(objType=="combobox" || objType == "autocomplete"){
                    if(value.length>4){
                        objId.setValue(value);
                    }
                    else{
                        objId.select(value);
                    }
                }
                else{
                    objId.setValue(value);
                }
            }




            /**
             * 设置默认选择
             */
            function setDefaultValue() {
                sendWayId.select(0);
                goodsTypeId.select(0);

                setObjValue(mini.get("dropAmount"),0.0);
                setObjValue(mini.get("settlementAmount"),0.0);
                setObjValue(mini.get("dropStatusId"),361);
                setObjValue(mini.get("settlementStatusId"),321);

                setObjValue(mini.get("freightAmountStatusId"),321);

            }

            /**
             * 选择承运方式
             * 根据选择的不同的承运方式加载不同的承运单位
             */
            function transportWayIdChange(){
                transportUnitId.load();
                let transportUnitIdJsonData;
                let cacheKey;
                let ids
                let enabledValue;
                let requiredValue;
                let transportWayIdValue = transportWayId.getValue();
                if(transportWayIdValue == transportWay.self){
                    // 自发，则加载公司缓存
                    cacheKey = "sysCompany";
                    // 同时把主单号的值填写到承运主单号上面，并锁定
                    ids = mini.get("id").getValue();
                    enabledValue = false;
                    requiredValue = true;
                }
                else{
                    // 这是外发，则需要加载外发单位
                    cacheKey = "outUnit";
                    ids = "";
                    enabledValue = true;
                    requiredValue = false;
                }
                transportUnitIdJsonData = commonRenderDropList(cacheKey);
                transportUnitId.load(transportUnitIdJsonData);
                transportUnitMasterBillCodeIds.setValue(ids);
                transportUnitMasterBillCodeIds.setEnabled(enabledValue);
                transportUnitMasterBillCodeIds.setRequired(requiredValue);
            }


            /**
             * 提货点选择
             * @param e
             */
            function pickUpPointIdChange(e){
                pickUpPointName.setValue(e.selected.name);
                pickUpPointPhone.setValue(e.selected.phone);
                pickUpPointAddress.setValue(e.selected.address);
            }


            /**
             * 获取焦点时发生
             */
            function billIdFocus(){
                if(isEmpty(destCityId,"目的站")){
                    return;
                }
                if(isEmpty(deliveryTime,"走货时间")){
                    return;
                }
                // 设置检索分单框的下拉列表查询条件
                setBillSearchCndUrl();
            }


            /**
             * 修改 billId 对象的检索 url
             * @returns {string}
             */
            function setBillSearchCndUrl(){
                let billIdUrl = baseUrl;
                let destCityIdValue = destCityId.getValue();
                // 这个地方的日期要处理成 yyyy-MM-dd 的格式
                let deliveryTimeValue = public_parseDateToString(deliveryTime.getValue(true),"YYYY-MM-DD");
                billIdUrl += "&destCityId=" + destCityIdValue;
                billIdUrl += "&flightDate=" + deliveryTimeValue;

                let existBillIds = "";
                if(billIdArray.length>0){
                    for(let billIdValue of billIdArray){
                        existBillIds += billIdValue + ",";
                    }
                    billIdUrl += "&existBillIds=" + existBillIds;
                }
                billId.setUrl(billIdUrl);
            }

            /**
             * 选择分单后的响应事件
             * @param e
             */
            function billIdChanged(e){
                let selectedItem = e.selected;
                if(public_isEmpty(selectedItem)){
                    billId.setValue();
                    return;
                }
                // 添加进去
                selectedBillDatagrid.addRow(selectedItem);

                // 把添加的分单加入主单的配载列表中
                setMasterBillLoadNativeBillIds();

                // 总值累计
                sumBillDatagrid();

                // 运费合计
                calcFreightAmount();

                // 设置查询条件
                setBillSearchCndUrl();

            }

            // 把添加的分单加入主单的配载列表中
            function setMasterBillLoadNativeBillIds(){
                let loadBillArray = selectedBillDatagrid.data;
                let loadNativeBillIdsValue = "";
                for(let obj of loadBillArray){
                    loadNativeBillIdsValue += obj.id + ",";
                }
                if(loadNativeBillIdsValue.length>0){
                    loadNativeBillIdsValue = loadNativeBillIdsValue.substr(0,loadNativeBillIdsValue.length-1);
                }
                mini.get("loadNativeBillIds").setValue(loadNativeBillIdsValue);
            }

            function sumBillDatagrid(){
                // 清空数组
                billIdArray.splice(0,billIdArray.length);
                // 求和计算
                let sumArray = selectedBillDatagrid.data;
                let sumTotalNumber=0;
                let sumActualWeight=0;
                let sumChargeableWeight=0;
                let sumActualLoadTotalWeight=0;
                let sumVolume=0;
                if(sumArray.length>0){
                    for(let i=0;i<sumArray.length;i++){
                        billIdArray.push(sumArray[i].id);
                        sumTotalNumber += sumArray[i].totalNumber;
                        sumActualWeight += sumArray[i].actualWeight;
                        sumChargeableWeight += sumArray[i].chargeableWeight;
                        sumActualLoadTotalWeight += sumArray[i].actualWeight;
                        sumVolume += sumArray[i].volume;
                    }
                }

                totalNumber.setValue(public_round2(sumTotalNumber));
                actualWeight.setValue(public_round2(sumActualWeight));
                chargeableWeight.setValue(public_round2(sumChargeableWeight));
                actualLoadTotalWeight.setValue(public_round2(sumActualLoadTotalWeight));
                volume.setValue(public_round2(sumVolume));

            }

            function removeSelectedRow(){
                let selectedRows = selectedBillDatagrid.getSelecteds();
                selectedBillDatagrid.removeRows(selectedRows);
                // 总值累计
                sumBillDatagrid();
                // 运费合计
                calcFreightAmount();

                // 把添加的分单加入主单的配载列表中
                setMasterBillLoadNativeBillIds();
            }

            function gridCellEndEdit(e){
                selectedBillDatagrid.data[e.rowIndex][e.field]=public_toNumber(e.value);
                // 总值累计
                sumBillDatagrid();

                // 运费合计
                calcFreightAmount();
            }

            function actualWeightChange(){
                calcFreightAmount();
            }

            function chargeableWeightChange(){
                calcFreightAmount();
            }

            function weightRateChange(){
                calcFreightAmount();
            }

            function volumeChange(){
                calcFreightAmount();
            }

            function volumeRateChange(){
                calcFreightAmount();
            }

            /**
             * 运费合计计算
             */
            function calcFreightAmount(){
                 if(isEmpty(actualWeight,"实际重量")
                     || isEmpty(chargeableWeight,"计费重量")
                     || isEmpty(weightRate,"重量费率")
                     || isEmpty(volume,"体积")
                     || isEmpty(volumeRate,"体积费率")){
                     return;
                 }

                let weightRateValue = public_toNumber(weightRate.getValue());
                let actualWeightValue = public_toNumber(actualWeight.getValue());
                let chargeableWeightValue = public_toNumber(chargeableWeight.getValue());
                let volumeValue = public_toNumber(volume.getValue());
                let volumeRateValue = public_toNumber(volumeRate.getValue());

                let calcWeight = actualWeightValue > chargeableWeightValue ? actualWeightValue : chargeableWeightValue;

                let freightAmountValue = calcWeight * weightRateValue > volumeRateValue * volumeValue ? public_decimal(calcWeight * weightRateValue,0) : public_decimal(volumeRateValue * volumeValue,0);

                // 设置运费合计值
                freightAmount.setValue(freightAmountValue);

                masterBillPaymentMethodIdChange();
            }

            /**
             * 增加其他费用
             */
            function addOtherChargesRow(){
                let newRow = {};
                otherChargeDatagrid.addRow(newRow);
                otherChargeDatagrid.beginEditCell(newRow, "name");
            }

            /**
             * 移除其他费用
             */
            function removeOtherChargesRow(){
                let rows = otherChargeDatagrid.getSelecteds();
                if (rows.length > 0) {
                    otherChargeDatagrid.removeRows(rows, true);
                    // 重新计算
                    calcOtherCharges();
                }
            }

            /**
             * 计算其他费用
             */
            function calcOtherCharges(){
                let otherChargeArray=otherChargeDatagrid.getData();

                if(otherChargeArray.length > 0){
                    let otherChargeTotal = 0;
                    let otherChargeComment = "";
                    for(let obj of otherChargeArray){
                        let tempAmount = public_toNumber(obj.amount,-1);

                        if(tempAmount == -1){
                            // 说明转成数值失败
                            showAlert("【其他费用】【金额】没有填写或填写了非数字值！");
                            return;
                        }
                        otherChargeTotal += tempAmount;
                        otherChargeComment += "{其他费用名目:" + obj.name + ",";
                        otherChargeComment += "金额:" + tempAmount + ",";
                        if(public_isEmpty(obj.comment)){
                            otherChargeComment += "备注: } ";
                        }
                        else{
                            otherChargeComment += "备注:" + obj.comment + "} ";
                        }

                    }

                    otherCharges.setValue(otherChargeTotal);
                    otherChargesComment.setValue(otherChargeComment);

                }
                else{
                    // 清空其他费用金额,及其他费用备注
                    otherCharges.setValue(0);
                    otherChargesComment.setValue("");
                }

                masterBillPaymentMethodIdChange();
            }

            /**
             * 计算总运费
             */
            function masterBillPaymentMethodIdChange(){
                if(isEmpty(freightAmount,"运费合计") || isEmpty(otherCharges,"其他费用")){
                    return;
                }

                if(isEmptyNoAlert(masterBillPaymentMethodId)){
                    totalFreightAmount.setValue(0);
                    masterBillPaymentMethodId.setValue();
                    return;
                }

                let freightAmountValue = public_toNumber(freightAmount.getValue());
                let otherChargesValue = public_toNumber(otherCharges.getValue());
                let totalFreightAmountValue = public_round2(freightAmountValue + otherChargesValue);



                // 设置总运费
                totalFreightAmount.setValue(totalFreightAmountValue);
            }

            function saveMasterBill(){
                masterBillForm.validate();
                if (masterBillForm.isValid() == false) {
                    return;
                }
                //提交数据
                let masterBillPojo = masterBillForm.getData(true);

                // settlementStatusId 如果主单已经结算，则不允许做任何调整,给出提示
                let settlementStatusId = masterBillPojo.settlementStatusId;
                if(settlementStatusId == settlementStatus.cleared){
                    showAlert("主单已结算，不能做保存操作!");
                    return;
                }

                if(masterBillPojo.chargeableWeight<=0){
                    showAlert("主单计费重量小于或等于零，不能保存主单!");
                    return;
                }

                // 获取其他费用列表
                let otherChargeList=otherChargeDatagrid.getData();
                masterBillPojo.otherChargeList = otherChargeList;

                // 获取主单包含的分单信息
                let nativeBillList = selectedBillDatagrid.getData();
                if(nativeBillList.length==0){
                    showAlert("主单下不包含分单，不能保存主单!");
                    return;
                }
                masterBillPojo.nativeBillList = nativeBillList;

                let opUrl ="${base}/pages/master_bill_manage/auto/addMasterAutoBill";
                if(opType=="update"){
                    opUrl ="${base}/pages/master_bill_manage/auto/updateMasterAutoBill";
                }

                mini.confirm("确定保存主单信息?","保存提示",function (action){
                    if (action == "ok") {
                        let msgId = mini.loading("正在保存, 请稍等 ...", "保存中");
                        let ret = public_getServerData(opUrl,masterBillPojo);
                        mini.hideMessageBox(msgId);
                        if(opType=="update"){
                            showAlert(ret.message,function (){
                                if(ret.ok){
                                    // 关闭编辑页面
                                    parent.window.closeActiveTab();
                                }
                            });
                        }
                        else{
                            showAlert(ret.message,function (){
                                if(ret.ok){
                                    // 刷新当前页面
                                    window.location.reload();
                                }
                            });
                        }
                    }
                });



            }

        </script>

    </body>
</html>